﻿#region MIT
/*
Engine Of Evermore (http://code.google.com/p/engineofevermore/)
Copyright (c) 2008, 2009 Michael Woerister

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
using System.Diagnostics;
using Platinum;
using EngineOfEvermore.Common;

namespace EngineOfEvermore.Editor.Common.Controls.PropertyEditors
{
    [IsDefaultPropertyEditorOf( typeof( Vector2d ) )]
    public partial class Vector2dEditor : PropertyEditorBase
    {
        #region Variables
        Platinum.IValidator _validator;
        BoundPropertyDescriptor _propertyDescriptor;
        Vector2d _newValue;
        Vector2d _oldValue;
        Vector2d _lastCommittedValue;
        IFormatProvider _formatProvider;
        bool _isXValueValid;
        bool _isYValueValid;
        bool _suppressChangeEvents;
        #endregion

        #region Properties
        public override BoundPropertyDescriptor PropertyDescriptor
        {
            get
            {
                return _propertyDescriptor;
            }
            set
            {
                if ( _propertyDescriptor == value )
                    return;

                _propertyDescriptor = value;

                RefreshProperty();
                
                _raisePropertyDescriptorChangedEvent( 
                    new PropertyDescriptorChangedEventArgs( value )
                    );
            }
        }
        #endregion

        #region Constructor
        public Vector2dEditor()
        {
            InitializeComponent();

            _validator = Platinum.Validators.DefaultValidator.CreateFor( typeof( float ) );
            _formatProvider = CultureInfo.GetCultureInfo( "en-US" ).NumberFormat;

            _propertyGridItemAssigned += new Action<PropertyGridItem>( _gridItemAssigned );
        }
        #endregion

        #region Methods
        public override void RefreshProperty()
        {
            if ( !_propertyDescriptor.IsEmpty )
            {
                _newValue =
                    (Vector2d) _propertyDescriptor.PropertyDescriptor.GetValue(
                        _propertyDescriptor.PropertyOwner
                        );

                _suppressChangeEvents = true;

                _xTextBox.Text = _newValue.X.ToString( _formatProvider );
                _yTextBox.Text = _newValue.Y.ToString( _formatProvider );

                _suppressChangeEvents = false;

                _oldValue = _newValue;
                _lastCommittedValue = _newValue;
            }
        }
        #endregion

        #region Event Handlers
        void _xTextBox_TextChanged( object sender, EventArgs e )
        {
            Object value = _validator.ValidateValue( _xTextBox.Text );

            if ( value == null )
            {
                _xTextBox.ForeColor = ErrorForeColor;
                _xTextBox.BackColor = ErrorBackColor;
                _xLabel.BackColor = ErrorBackColor;
                _isXValueValid = false;
            }
            else
            {
                _xTextBox.ForeColor = Color.FromKnownColor( KnownColor.ControlText );
                _xTextBox.BackColor = Color.FromKnownColor( KnownColor.Window );
                _xLabel.BackColor = Color.FromKnownColor( KnownColor.Window );

                _isXValueValid = true;

                float newXValue = (float) value;

                if ( newXValue != _newValue.X )
                {
                    _oldValue = _newValue;
                    _newValue.X = newXValue;

                    if ( !_suppressChangeEvents )
                    {
                        _raisePropertyChangingEvent(
                            new PropertyChangeEventArgs( _oldValue, _newValue )
                            );
                    }
                }
            }
        }

        void _yTextBox_TextChanged( object sender, EventArgs e )
        {
            Object value = _validator.ValidateValue( _yTextBox.Text );

            if ( value == null )
            {
                _yTextBox.ForeColor = ErrorForeColor;
                _yTextBox.BackColor = ErrorBackColor;
                _yLabel.BackColor = ErrorBackColor;
                _isYValueValid = false;
            }
            else
            {
                _yTextBox.ForeColor = Color.FromKnownColor( KnownColor.ControlText );
                _yTextBox.BackColor = Color.FromKnownColor( KnownColor.Window );
                _yLabel.BackColor = Color.FromKnownColor( KnownColor.Window );

                _isYValueValid = true;

                float newYValue = (float) value;

                if ( newYValue != _newValue.Y )
                {
                    _oldValue = _newValue;
                    _newValue.Y = newYValue;

                    if ( !_suppressChangeEvents )
                    {
                        _raisePropertyChangingEvent(
                            new PropertyChangeEventArgs( _oldValue, _newValue )
                            );
                    }
                }
            }
        }

        void Vector2dEditor_Load( object sender, EventArgs e )
        {
            _suppressChangeEvents = true;

            _xTextBox.Text = _newValue.X.ToString();
            _yTextBox.Text = _newValue.Y.ToString();

            _suppressChangeEvents = false;
        }

        void _xTextBox_KeyDown( object sender, KeyEventArgs e )
        {
            if ( e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return )
            {
                e.Handled = true;
                e.SuppressKeyPress = true;

                if ( _isXValueValid && _isYValueValid )
                {
                    _commitChange();
                }
                else
                {
                    System.Media.SystemSounds.Beep.Play();
                }
            }
            else if ( e.KeyCode == Keys.Escape )
            {
                e.Handled = true;
                _revertChange();
            }
            else
            {
                e.Handled = false;
            }
        }

        void _yTextBox_KeyDown( object sender, KeyEventArgs e )
        {
            _xTextBox_KeyDown( _yTextBox, e );
        }

        void _xTextBox_Leave( object sender, EventArgs e )
        {
            _tryCommitChange();
        }

        void _yTextBox_Leave( object sender, EventArgs e )
        {
            _tryCommitChange();
        }

        void _gridItemAssigned( PropertyGridItem item )
        {
            Platinum.PropertyGrid grid = item.Owner.Owner;

            BackColor = grid.SectionBackColor;

            grid.SectionBackColorChanged += _grid_SectionBackColorChanged;

            item.IsSelectedChanged += new EventHandler( _item_IsSelectedChanged );
        }

        void _item_IsSelectedChanged( object sender, EventArgs e )
        {
            if ( PropertyGridItem.IsSelected )
            {
                _xTextBox.Focus();
            }
        }

        void _grid_SectionBackColorChanged( object sender, ColorChangedEventArgs e )
        {
            BackColor = e.NewColor;
        }
        #endregion

        #region Private Methods
        void _tryCommitChange()
        {
            if ( _isXValueValid && _isYValueValid )
            {
                _commitChange();
            }
            else
            {
                _revertChange();
            }
        }

        void _commitChange()
        {
            Debug.Assert( _isXValueValid && _isYValueValid );

            Vector2d oldValue = _lastCommittedValue;
            _lastCommittedValue = _newValue;

            _raisePropertyChangeCommittedEvent(
                new PropertyChangeEventArgs( oldValue, _lastCommittedValue )
                );
        }

        void _revertChange()
        {
            _suppressChangeEvents = true;

            _xTextBox.Text = _newValue.X.ToString();
            _yTextBox.Text = _newValue.Y.ToString();

            _suppressChangeEvents = false;

            _raisePropertyChangeRevertedEvent(
                new PropertyChangeRevertedEventArgs( _lastCommittedValue )
                ); 
        }
        
        #endregion
    }
}
